from ApiTestEngine.core2.cases import run_test
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.views import APIView

from Scenes.models import TestScene, TestSceneToCase
from Scenes.serializers import TestSceneSerializer, TestSceneToCaseSerializer, TestSceneToCaseGetSerializer, \
    TestSceneRunSerializer
from rest_framework import permissions, mixins

from Testproject.models import TestEnvModel


# Create your views here.


class TestSceneView(mixins.CreateModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    mixins.ListModelMixin,
                    GenericViewSet):
    queryset = TestScene.objects.all()
    serializer_class = TestSceneSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ["project"]

    def run_scene(self, request):
        # 获取接口参数并校验
        env_id = request.data.get("env")
        scene_id = request.data.get("scene")
        if not env_id:
            return Response({"msg": "env参数不能为空"}, status=400)
        if not scene_id:
            return Response({"msg": "scene参数不能为空"}, status=400)
        # 组装ENV
        env = TestEnvModel.objects.get(id=env_id)
        env_config = {
            "ENV": {
                "host": env.host,
                "headers": env.headers,
                **env.global_variable,
            },
            "DB": env.db,
            "global_func": env.global_func
        }
        # 获取scene中用例
        scene = TestScene.objects.get(id=scene_id)
        cases = scene.testscenetocase_set.all()
        res = TestSceneRunSerializer(cases, many=True).data
        # 用例排序
        datas = sorted(res, key=lambda x: x["sort"])
        # 组装case_data
        case_data = [{
            "name": scene.name,
            "Cases": [x['icase'] for x in datas]
        }
        ]
        r = run_test(case_data, env_config, debug=False)
        return Response(r['results'][0], status=200)
        # 执行引擎


class TestSceneToCaseView(mixins.CreateModelMixin,
                          mixins.UpdateModelMixin,
                          mixins.DestroyModelMixin,
                          mixins.ListModelMixin,
                          GenericViewSet):
    queryset = TestSceneToCase.objects.all()
    serializer_class = TestSceneToCaseSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['scene']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = TestSceneToCaseGetSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = TestSceneToCaseGetSerializer(queryset, many=True)
        return Response(serializer.data)


class TestSceneToCaseModifyView(APIView):
    def put(self, request):
        info = request.data
        for item in info:
            obj = TestSceneToCase.objects.get(id=item['id'])
            obj.sort = item['sort']
            obj.save()
        return Response(info)
